#include <drivers/pin.h>
#include <rtthread.h>
#include <rtconfig.h>
#include <rtdevice.h>
#include <wiegand.h>
#include <pin.h>


#define WIEGAND_DEMO_THD_NAME		"wgdemo"
#define WIEGAND_DEMO_THD_STACK		512
#define WIEGAND_DEMO_THD_PRI		21
#define WIEGAND_DEMO_THD_TICK		10
#define WIEGAND_DEMO_MAILBOX_SIZE 	8
#define WIEGAND_DEMO_BUF_SIZE		64

rt_mailbox_t mb_wg=RT_NULL;

void wiegand_demo_entry(void *para)
{
	static rt_uint8_t buf[WIEGAND_APP_BUF_SIZE]={0};
	rt_uint32_t addr;
	rt_err_t ret;
	
	while(1)
	{
		rt_memset(buf,0,WIEGAND_APP_BUF_SIZE);
		ret=rt_mb_recv(mb_wg,&addr,RT_WAITING_FOREVER);
		if(RT_EOK==ret)
		{
			rt_memcpy(buf,(rt_uint8_t*)addr,WIEGAND_APP_BUF_SIZE);
			LOG_E("got a wiegand reader data from %s",PKG_WIEGAND_DEMO_DEV_NAME);
			,,,,,,
		}
	}
}

rt_err_t wiegand_demo_rx_indicate(rt_device_t dev, rt_size_t size)
{
	static rt_uint8_t buf[WIEGAND_APP_BUF_SIZE]={0};

	if(size>WIEGAND_APP_BUF_SIZE)
	{
		return -RT_ENOMEM;
	}
	rt_memset(buf,0,WIEGAND_APP_BUF_SIZE);
	rt_device_read(dev,0,buf,size);
	rt_mb_send(mb_wg,buf);
	return size;
}

rt_err_t wiegand_demo_init(void)
{
	wiegand_package *wiegand=RT_NULL;
	rt_device_t dev=RT_NULL;
	rt_thread_t thd=RT_NULL;
	rt_err_t ret;
	
	/* 设置wiegand读头的中断响应引脚 */
	rt_pin_mode(PKG_WIEGAND_DEMO_IRQ_PIN,PIN_MODE_INPUT);
	/* 设置wiegand读头的D0的响应引脚 */
	rt_pin_mode(PKG_WIEGAND_DEMO_D0_PIN,PIN_MODE_INPUT);
	/* 安装wiegand驱动 */
	ret=wiegand_device_init(PKG_WIEGAND_DEMO_DEV_NAME,
		PKG_WIEGAND_DEMO_DATA_BIT,PKG_WIEGAND_DEMO_D0_PIN);
	if(RT_EOK!=ret)
	{
		LOG_E("wiegand init for %s fail",PKG_WIEGAND_DEMO_DEV_NAME);
		return -RT_EIO;
	}
	/* 获取wiegand指针并挂载到中断响应引脚对应的驱动 */
	dev=rt_device_find(PKG_WIEGAND_DEMO_DEV_NAME);
	if(RT_NULL==dev)
	{
		LOG_E("find device %s fail",PKG_WIEGAND_DEMO_DEV_NAME);
		return -RT_EIO;
	}
	wiegand=(wiegand_package*)(dev->user_data);
	if(RT_NULL==wiegand)
	{
		LOG_E("wiegand %d user_data is null",PKG_WIEGAND_DEMO_DEV_NAME);
		return -RT_ENOMEM;
	}
	
	/* 安装接收回调  */
	rt_device_set_rx_indicate(dev,wiegand_app_rx_indicate);

	mb_wg=rt_mb_create("wiegand",WIEGAND_MAILBOX_SIZE,RT_IPC_FLAG_FIFO);
	if(RT_NULL==mb_wg)
	{
		LOG_E("mailbox create fail");
		return -RT_EEMPTY;
	}
	thd=rt_thread_create(WIEGAND_APP_THD_NAME
			,wiegand_thread_entry,RT_NULL,WIEGAND_APP_THD_STACK
			,WIEGAND_APP_THD_PRI,WIEGAND_APP_THD_TICK);
	if(RT_NULL==thd)
	{
		LOG_E("create wiegand app for %s fail",PKG_WIEGAND_DEMO_DEV_NAME);
		return -RT_ENOMEM;
	}
	rt_thread_startup(thd);
	/* 注意:
	 1 必须安装wiegand的中断方式为下降沿
	 2 所有工作都准备完毕之后再开动硬件中断
	*/
	rt_pin_attach_irq(PKG_WIEGAND_DEMO_IRQ_PIN,PIN_IRQ_MODE_FALLING,
		wiegand_irq_isr,wiegand);
	rt_pin_irq_enable(PKG_WIEGAND_DEMO_IRQ_PIN,PIN_IRQ_ENABLE);;
}

INIT_APP_EXPORT(wiegand_demo_init);

